

$(function () {
	$("#add_form").submit(function () {
		var data = {
			"login" : $("#new_login").val(),
			"password" : $("#new_password").val(),
			"info" : $("#new_info").val()
		};
		var passwd = $("#master_passwd").val();
//		if (raw_data.length == 0) {
//			return enqrypt.error("Input something to encrypt!");
//		}
		if (passwd.length == 0) {
			return enqrypt.error("Enter a master password!");
		}
		var enc = enqrypt.encrypt(data, passwd);
		$("#data").val(JSON.stringify(enc));
		$("#service").val($("#new_service").val());
	});

	$("#master_passwd").keyup(function () {
			$("#data_container tbody tr").each(function () {
				var self = $(this);
				if ($(".do_decrypt", self)[0].checked) {
					enqrypt.decrypt(self.attr("id"));
				}
			});

	});

});


var enqrypt = {
	mode : slowAES.modeOfOperation.CBC,
	key_length : 160,
	max_int : 256,
	error : function (msg) {
		alert(msg);
		return false;
	},
	to_bytes : function (string) {
		var array = [];
		var escaped = encodeURIComponent(string);
		for (var i = 0; i < escaped.length; i++) {
			array.push(escaped.charCodeAt(i));
		}
		return array;
	},
	encrypt : function (data_dict, passwd) {
					// init iv with random numbers
					var iv = [];
					for (var i = 0; i < enqrypt.key_length; i++) {
						iv.push(Math.floor(Math.random()*enqrypt.max_int));
					}
					var enc = { iv : iv };
					var passwd_bytes = enqrypt.to_bytes(passwd);

					for (var key in data_dict) {
						enc[key] = slowAES.encrypt(enqrypt.to_bytes(data_dict[key]), enqrypt.mode, passwd_bytes, iv);
					}
					return enc;
				},

	decrypt : function (key) {

		var iv = JSON.parse($("#"+key+" .iv").text());
		var passwd_bytes = enqrypt.to_bytes($("#master_passwd").val());

		function decrypt_data(data) {

			var dec_bytes = slowAES.decrypt(data,
											enqrypt.mode,
											passwd_bytes,
											iv);
			var dec_data = "";
			for (var i = 0; i < dec_bytes.length; i++) {
				dec_data += String.fromCharCode(dec_bytes[i]);
			}
			var decrypted = "";
			try {
				decrypted = decodeURIComponent(dec_data);
			} catch(e) {
				decrypted = "Encrypted";
			}
			return decrypted;
		}
		$("#"+key+" .enc_data").each(function () {
			var self = $(this);
			$(".dec_data", self.parent()).text(decrypt_data(JSON.parse(self.text())));

		});


		
	},

	decrypt_ : function (enc_data, iv, passwd) {
		return slowAES.decrypt(enc_data, enqrypt.mode, passwd, iv);
	}
}